import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// 一级路由
import Login from '@/views/Login'
import Register from '@/views/Register'
import Layout from '@/views/Layout'
// 二级路由
import Advice from '@/views/second/Advice'
import Home from '@/views/second/Home'
import House from '@/views/second/House'
import User from '@/views/second/User'

import Favorites from '@/views/UserGrid/Favorites'
import MyHire from '@/views/UserGrid/MyHire'
import ViewRecords from '@/views/UserGrid/ViewRecords'
import HouseOwner from '@/views/UserGrid/HouseOwner'
import PersonalData from '@/views/UserGrid/PersonalData'
import ContactUs from '@/views/UserGrid/ContactUs'

Vue.use(VueRouter)

const routes = [
// 一级路由
  //  path: 路径 , component: 组件名
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    // 路径为 '/' 表示 默认地址
    path: '/',
    component: Layout,
    redirect: '/home',
    // 二级路由
    children: [
      { path: '/home', component: Home },
      { path: '/advice', component: Advice },
      { path: '/house', component: House },
      { path: '/user', component: User }
    ]
  },
  { path: '/favorites', component: Favorites },
  { path: '/myHire', component: MyHire },
  { path: '/viewRecords', component: ViewRecords },
  { path: '/houseOwner', component: HouseOwner },
  { path: '/personalData', component: PersonalData },
  { path: '/contactUs', component: ContactUs }

]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register', '/', '/advice', '/home', '/house', '/user']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
